/**
 * Copyright 2014 @ z3q.net.
 * name :
 * author : jarryliu
 * date : 2013-12-12 16:52
 * description :
 * history :
 */

package seller

import (
    "dhfshop/models"
	"strings"
	"errors"
	"time"
	"github.com/astaxie/beego/orm"
)

//库存表
type Stock struct {
	ItemId       int64      `orm:"column(item_id);pk;auto" json:"item_id" form:"item_id"`     /* 商品编号 */
	CompanyId    int64        `orm:"column(company_id)" json:"company_id" form:"company_id"`    //供应商ID
	SkuId        int64      `orm:"column(sku_id)" json:"sku_id" form:"sku_id"`                 /* 规格编号 */
	CategoryId   int64      `orm:"column(category_id)" json:"category_id" form:"category_id"`  /* 分类 */
	StockNum     int        `orm:"column(stock_num)" json:"stock_num" form:"stock_num"`        /* 总库存 */  
	StockDetail  string     `orm:"column(stock_detail)" json:"stock_detail" form:"stock_detail"` /* 子仓库的详情,json串:{name1:num1;name2:num2} */              
	CreatedAt    time.Time  `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"`   /* 创建时间 */
	CreatedAtStr string     `orm:"-" json:"created_at" form:"-"`
	UpdatedAt    time.Time  `orm:"auto_now;column(updated_at);type(datetime)" json:"-" form:"-"` 
	UpdatedAtStr string     `orm:"-" json:"updated_at" form:"-"`
}

func init() {
    orm.RegisterModel(new(Stock))   
}

func AddStock(m *Stock) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetStockById(id int64) (v *Stock, err error) {
	o := models.GetDefaultDB()
	v = &Stock{ItemId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAllStocks(query map[string]string, fields []string, order_by map[string]string, 
    offset int, limit int) ([]*Stock, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Stock))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*Stock
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateStockById(m *Stock, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := Stock{ItemId: m.ItemId}
	if err = o.Read(&v); err != nil {
		return err
	}else{
	    if _, err = o.Update(m, k...); err != nil {
		   return err
		}
	}
	return nil
}

func DeleteStock(id int64) (err error) {
	o := models.GetDefaultDB()
	v := Stock{ItemId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}
